package com.zenithmind.news.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * WebSocket配置类 - 重构后遵循依赖倒置原则
 * 依赖抽象接口而非具体实现，提高可扩展性
 *
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Configuration
@EnableWebSocket
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketConfigurer {

    private final WebSocketHandler newsWebSocketHandler;
    private final HandshakeInterceptor webSocketInterceptor;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册新闻推送WebSocket处理器
        // 使用NewsEndpointConfig中定义的端点路径
        registry.addHandler(newsWebSocketHandler, NewsEndpointConfig.WEBSOCKET_ENDPOINTS)
                .addInterceptors(webSocketInterceptor)
                .setAllowedOrigins("*"); // 生产环境应该配置具体的域名
    }
}
